<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="openDialog(0)">添加权限</el-button>
      <el-table :data="permissionList" row-key="id" default-expand-all>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button v-if="row.type === 1" size="middle" type="text" @click="openDialog(row.id)">添加</el-button>
            <el-button size="middle" type="text" @click="openDialog(row.id, true)">编辑</el-button>
            <el-button size="middle" type="text" @click="delPermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增和编辑权限点的弹层 -->
    <PermissionDialog
      :id="id"
      ref="pmsDialog"
      :show-dialog.sync="showDialog"
      :pms-name-list="pmsNameList"
      :pms-code-list="pmsCodeList"
      @refresh="getPermissionList"
    />
  </div>
</template>
<script>
import { deletePermissionApi, getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import PermissionDialog from './components/PermissionDialog.vue'
export default {
  name: 'Permission',
  components: {
    PermissionDialog
  },
  data() {
    return {
      permissionList: [],
      showDialog: false,
      pmsNameList: [],
      pmsCodeList: [],
      id: null
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListApi()
      // 提取出权限点名字数组及权限标识数组
      this.pmsNameList = res.map(item => item.name)
      this.pmsCodeList = res.map(item => item.code)
      this.permissionList = transListToTreeData(res, 0)
    },
    openDialog(id, isEdit = false) {
      this.showDialog = true
      // 记录当前点击的权限点的id
      this.id = id
      if (isEdit) {
        // 编辑权限点
        this.$refs.pmsDialog.getPermissionDetail(id)
      }
    },
    delPermission(id) {
      this.$confirm('确定要删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        await deletePermissionApi(id)
        this.$message.success('删除成功')
        this.getPermissionList()
      }).catch(() => {
      })
    }
  }
}
</script>

<style>
.btn-add {
  margin: 10px;
}
</style>
